<?php

declare(strict_types=1);

namespace App\Orchid\Filters;

use App\Models\Category;
use Illuminate\Database\Eloquent\Builder;
use Orchid\Filters\Filter;
use Orchid\Screen\Fields\Select;

class PostCategoryFilter extends Filter
{
    /**
     * The displayable name of the filter.
     *
     * @return string
     */
    public function name(): string
    {
        return '分类';
    }

    /**
     * The array of matched parameters.
     *
     * @return array
     */
    public function parameters(): array
    {
        return ['category_id'];
    }

    /**
     * Apply to a given Eloquent query builder.
     *
     * @param Builder $builder
     *
     * @return Builder
     */
    public function run(Builder $builder): Builder
    {
        $categoryId = $this->request->get('category_id');
        
        if (empty($categoryId)) {
            return $builder;
        }
        
        return $builder->where('category_id', $categoryId);
    }

    /**
     * Get the display fields.
     */
    public function display(): array
    {
        return [
            Select::make('category_id')
                ->fromModel(Category::class, 'name')
                ->empty('全部分类')
                ->value($this->request->get('category_id'))
                ->title('分类'),
        ];
    }

    /**
     * Value to be displayed
     */
    public function value(): string
    {
        $category = Category::find($this->request->get('category_id'));
        return $this->name() . ': ' . ($category ? $category->name : '');
    }
}